<?php


namespace App\Lib\file;

use App\Models\lin\LinFile;
use Illuminate\Support\Facades\Storage;

class LocalUploader extends File
{
    public function upload()
    {
        $ret = [];
        $date = date('Y').'/'.date('m').'/'.date('d');
        $host = env('FILE_HOST');
        foreach ($this->files as $key => $file) {
            $md5 = md5_file($file->getRealPath());
            $exists = LinFile::whereMd5($md5)->first();
            if ($exists) {
                array_push($ret, [
                    'id' => $exists['id'],
                    'key' => $key,
                    'path' => $exists['path'],
                    'url' => $host . '/' . $this->storeDir . '/' . $exists['path']
                ]);
            } else {
                $filename = md5(time() . rand(100000, 999999)) . '.' . $file->getClientOriginalExtension();
                $uploadPath = public_path() . '/' . $this->storeDir . '/'. $date;
                $info = $file->move($uploadPath, $filename); //移动至指定目录

                $path = $date . '/' . $info->getFileName();
                $linFile = LinFile::create([
                    'name' => $filename,
                    'path' => $path,
                    'size' => $info->getSize(),
                    'extension' => $info->getExtension(),
                    'md5' => $md5,
                    'type' => 'LOCAL'
                ]);
                array_push($ret, [
                    'id' => $linFile->id,
                    'key' => $key,
                    'path' => $path,
                    'url' => $host . '/' . $this->storeDir . '/'. $date. '/' . $info->getfileName()
                ]);
            }
        }
        return $ret;
    }
}
